<template>
    <div class="detail-main">
        <div class="detail-box">
            <div class="f-box">
                <!-- <img :src="imagePath(data.shelfs)" alt=""> -->
                <div class="cover" style="align-self: stretch; background-color: white; cursor: pointer">
                    <PDFImage v-if="!isLoading && data.shelfs && pdfPath(data.shelfs)" :src="pdfPath(data.shelfs)" />
                    <img v-else-if="!isLoading" src="demo.png" style="width: 100%;" alt="">
                </div>
                <div class="info">
                    <h4 class="hand" @click="toInstanceSearch('title',data.title)">{{data.title}}</h4>
                    <p v-if="data.parallelTitles&&data.parallelTitles.length>0">
                        <span >并列题名：</span>
                        <span v-for="(item,index) in data.parallelTitles" :key="index+'6'" v-show="item.title" style="color: #4c4c4c">
                            {{item.title}}&nbsp;&nbsp;&nbsp;
                        </span>
                    </p>
                    <p v-if="data.personInfoList&&data.personInfoList.length>0">
                        <span>责任者：</span>
                        <span v-for="(item, index) in data.personInfoList" :key="index+'1'" v-show="item.personUri">
                            <span v-if="item.personUri.indexOf('/mgts/')>-1" style="color: #4c4c4c">{{item.personName}}</span>
                            <span v-else @click="toContributionPerson(item.personUri)" style="color: #4c4c4c; border-bottom: 1px solid #000; text-decoration:none" class="hand">{{item.personName}}</span>
                            <span v-if="item.personRole" style="color: #4c4c4c">({{item.personRole}})&nbsp;&nbsp;&nbsp;</span>
                            <span v-else style="color: #4c4c4c">&nbsp;&nbsp;&nbsp;</span>
                        </span>
                    </p>
                    <p v-if="data.provisionActivityList&&data.provisionActivityList.length>0&&data.provisionActivityList[0].proPlace">
                        <span>出版地：</span>
                        <span v-for="(item, index) in data.provisionActivityList" :key="index+'3'" v-show="item.proPlace" style="color: #4c4c4c">
                            {{item.proPlace}}&nbsp;&nbsp;&nbsp;
                        </span>
                    </p>
                    <p v-if="data.provisionActivityList&&data.provisionActivityList.length>0&&data.provisionActivityList[0].proOrganization">
                        <span>出版社：</span>
                        <span v-for="(item, index) in data.provisionActivityList" :key="index+'2'" v-show="item.proOrganization" style="color: #4c4c4c" class="hand" @click="toInstanceSearch('publisher',item.proOrganization)">
                            {{item.proOrganization}}&nbsp;&nbsp;&nbsp;
                        </span>
                    </p>
                    <p v-if="data.provisionActivityList&&data.provisionActivityList.length>0&&data.provisionActivityList[0].proDate">
                        <!-- <span>出版时间：</span>
                        <span v-for="(item, index) in data.provisionActivityList" :key="index+'4'" v-show="item.proDate" style="color: #4c4c4c">
                            {{item.proDate}}&nbsp;&nbsp;&nbsp;
                        </span> -->
                        <span v-show="data.provisionActivityList[0].proDate">出版时间：<span style="color: #4c4c4c">{{data.provisionActivityList[0].proDate}}</span></span>
                    </p>
                    <p v-if="data.publications&&data.publications.length>0">
                        <span >发行制作机构：</span>
                        <span v-for="(item,index) in data.publications" :key="index+'7'" v-show="item.publish" style="color: #4c4c4c" class="hand" @click="toInstanceSearch('publication',item.publish)">
                            {{item.publish}}&nbsp;&nbsp;&nbsp;
                        </span>
                    </p>
                    <p v-if="data.subject&&data.subject.length>0">
                        <span >主题词：</span>
                        <span v-for="(item,index) in data.subject" :key="index+'8'" v-show="item" style="color: #4c4c4c" class="hand" @click="toInstanceSearch('theme',item)">
                            <span v-show="index!=0">；</span>{{item}}
                        </span>
                    </p>
                    <!-- <p v-if="data.subject" class="hand" @click="toInstanceSearch('theme',data.subject)"><span>主题词：</span>{{data.subject}}</p> -->
                    <p v-if="data.workSummary"><span>内容提要：</span>{{data.workSummary}}</p>
                    <p v-if="data.dimensions"><span>尺寸：</span>{{data.dimensions}}</p>
                    <p v-if="data.page"><span>页码：</span>{{data.page}}</p>
                    <p v-if="data.language"><span>语种：</span>{{data.language}}</p>
                    <!-- <p v-if="data.terms"><span>定价：</span>{{data.terms}}</p> -->
                    <p v-if="data.classPortion&&data.classPortion.length>0">
                        <span >分类号：</span>
                        <span v-for="(item,index) in data.classPortion" :key="index+'9'" v-show="item" style="color: #4c4c4c">
                            {{item}}&nbsp;&nbsp;&nbsp;
                        </span>
                    </p>
                    <!-- <p v-if="data.classCode"><span>分类号：</span>{{data.classCode}}</p> -->
                    <p v-if="data.series"><span>丛书项：</span>{{data.series}}</p>
                    <div class="flx" v-if="data.shelfs&&data.shelfs.length>0">
                        <span style="color: #666">索书号：</span>
                        <ul>
                            <li v-for="(item,index) in data.shelfs" :key="index+'5'" v-show="item.shelfmark">
                                {{index+1}}.&nbsp;&nbsp;&nbsp;{{item.shelfmark}}
                                <span v-if="item.identifier">(全文标识：{{ item.identifier }})&nbsp;</span>
                                <!-- <a v-if="item.fullTextPath" @click="checkDownload(item.fullTextPath,data.title)">
                                    <img style="width:15px;height:15px;margin-bottom:3px;" src="pdf.png"/>
                                </a> -->
                                <a v-if="item.fullTextFlag" @click="pdfView(item.fullTextFlag,item.fullTextPath)" title="点击查看PDF全文">
                                    <img style="width:15px;height:15px;margin-bottom:3px;" src="pdf2.png"/>
                                </a>
                            </li>
                        </ul>
                    </div>
                </div>
            </div>
            <router-link :to="{name: 'moreVersion', query: {uri: data.workUri}}" target="_blank" v-if="data.workUri">
                <div class="btm-tit" style="color: #666">作品：{{data.workTitle}}</div>
            </router-link>
        </div>
        <a-modal v-model="visibleUser" :closable="false" :keyboard="false" :maskClosable="false" width="20%" title="消息" @ok="login">
            <template slot="footer"><a-button key="submit" type="primary" @click="ConfirmError">确认</a-button></template>
            <p class="failure">获取用户信息出错，请联系管理员！</p>
        </a-modal>
        <a-modal v-model="visibleLook" :closable="false" :keyboard="false" :maskClosable="false" width="20%" title="消息" @ok="logout">
            <template slot="footer"><a-button key="submit" type="primary" @click="logout">确认</a-button></template>
            <p class="failure">您无权访问此站点！</p>
        </a-modal>
        <a-modal v-model="visibleCheck" :closable="false" :keyboard="false" :maskClosable="false" width="20%" title="消息" @ok="visibleCheck=false">
            <template slot="footer"><a-button key="submit" type="primary" @click="visibleCheck=false">确认</a-button></template>
            <p class="failure">{{checkErrorMsg}}</p>
        </a-modal>
        <a-modal v-model="visibleCode" :closable="false" :keyboard="false" :maskClosable="false" width="20%" :title="checkErrorMsg" @ok="identify" @cancel="cancel">
            <template slot="footer">
                <a-button key="cancel" type="default" @click="cancel">取消</a-button>
                <a-button key="submit" type="primary" @click="identify">确认</a-button>
            </template>
            <a-input size="large" placeholder="请输入验证码（点击图片刷新）" style="width:300px;margin-bottom:10px;" v-model="inputCode" @keyup.enter="identify"/>
            <img :src="codeImg" style="width:300px;margin-bottom:10px;cursor:pointer;" alt="" @click="changeImg" />
            <p class="failure" v-if="showErrorCode" style="margin:0;font-size:16px;font-weight:bold;">{{errorCodeMsg}}</p>
        </a-modal>
    </div>
</template>

<script>
import axios from "axios";
import { accountAuthtication, downloadAsk, instance, reportPreview, validCode } from "../../api/urls";
import PDFImage from "../../components/PDFImage.vue";
import { getCookie } from "../../utils/cookies";
export default {
  components: { PDFImage },
  data() {
    return {
        uri: this.$route.query.uri,
        isLoading: true,
        data: '',
        visibleLook: false,
        visibleUser: false,
        visibleCheck: false,
        visibleCode: false,
        checkErrorMsg: '',
        codeImg: '',
        randomNum: '',
        inputCode: '',
        showErrorCode: false,
        errorCodeMsg: '',
        fullTextPath: "",
        fullTextTitle: ""
    };
  },

  created() {
    this.checkUser()
    this.getInstanceDetail()
    this.createRandom()
  },

  mounted() {
      
  },

  computed: {
    imagePath() {
        return function(shelfs) {
            let path = ""
            if(shelfs&&shelfs.length>0) {
                for (let i = 0; i < shelfs.length; i++) {
                    if(shelfs[i].cover) {
                        path = "//jdts.library.sh.cn/cover/" + shelfs[i].cover
                        break
                    }
                }
                if(path) {
                    return path
                } else {
                    return "demo.png"
                }
            } else {
                return "demo.png"
            }
        }
    }
},

  methods: {
    pdfPath(shelfs) {
      if(shelfs && shelfs.length > 0) {
        for (let i = 0; i < shelfs.length; i++) {
          if(shelfs[i].identifier) {
              return `https://dhapi.library.sh.cn/service_pdf/pdf/mgts/cover?callNo=${shelfs[i].identifier}`
          }
        }
      }
      return null;
    },
    async checkDownload(fullTextPath,title) {
        this.fullTextPath = fullTextPath
        this.fullTextTitle = title
        if(sessionStorage.getItem('viewPermission')=="false") {
            this.checkErrorMsg = "您无权限访问此资源"
            this.visibleCheck = true
        } else {
            await axios.get(downloadAsk, {params: {token: sessionStorage.getItem('token')}}).then(response => {
                // 0:正常、-1:无权限，-2:需要验证码，-3:xx时间内无法浏览，4:禁止浏览
                if (response.data.status==0) {
                    window.open("https://www.cnbksy.com/literature/browseEntityJdts/"+this.fullTextPath+"?token="+sessionStorage.getItem('token')+"&ti="+this.fullTextTitle, "_blank");
                    // 全文浏览埋点
                    // this.buryingPoint()
                } else if(response.data.status==-2) {
                    this.checkErrorMsg = response.data.msg
                    this.errorCodeMsg = ''
                    this.inputCode = ''
                    this.createRandom()
                    this.showErrorCode = false
                    this.visibleCode = true
                } else { // -1, -3, -4
                    this.checkErrorMsg = response.data.msg
                    this.visibleCheck = true
                }
            });
        }
    },

    async identify() {
        await axios.get(validCode, {params: {
            t: this.randomNum,
            code: this.inputCode
        }}).then(response => {
            if (response.data.status==0) {
                this.visibleCode = false
                window.open("https://www.cnbksy.com/literature/browseEntityJdts/"+this.fullTextPath+"?token="+sessionStorage.getItem('token')+"&ti="+this.fullTextTitle, "_blank");
                // 全文浏览埋点
                // this.buryingPoint()
            } else {
                this.errorCodeMsg = response.data.msg
                this.showErrorCode = true
            }
        });
    },
    pdfView(flag, callNo){
        if(flag == 1) {
            window.open("https://dhapi.library.sh.cn/pdfview?dbname=mgts&type=callno&idvalue="+callNo+`&token=${sessionStorage.getItem('token') || ""}`);
        } else if(flag == 2) {
            //去登陆
            this.login();
        }
    },
    cancel() {
        this.visibleCode = false
    },

    createRandom() {
        let chars = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
        let nums=""
        for(let i=0;i<16;i++){ //这里是几位就要在这里不改变
            let id = parseInt(Math.random()*61);
            nums+=chars[id];
        }
        this.randomNum = nums
        this.codeImg = "https://www.cnbksy.com/kaptcha.jpg?t="+nums
    },

    changeImg() {
        this.createRandom()
    },

    async getInstanceDetail() {
        // await axios.post("api/instance", {data: this.uri}).then(response => {
        await axios.post(instance, {data: this.uri}).then(response => { // chenss 20240327
            if (response.data.success) {
                const data = response.data.data;
                let isInner = response.data.privateIP;
                if(data.shelfs && data.shelfs.length>0) {
                    data.shelfs.sort((a, b) => a.shelfmark > b.shelfmark ? 1 : -1);
                    for (let i = 0; i < data.shelfs.length; i++) {
                        let s_item = data.shelfs[i];
                        s_item.fullTextFlag = "";
                        if(s_item.accessLevel == "1" && isInner) {
                            s_item.fullTextFlag = 1;
                        } else if(s_item.accessLevel == "0" ) {
                            if(isInner || sessionStorage.getItem('token')) {
                                s_item.fullTextFlag = 1;
                            }else{
                                s_item.fullTextFlag = 2;
                            }
                        }
                    }
                }
                this.data = data;
            } else {
                this.$message.error("System Error")
            }
        }).finally(() => {
            this.isLoading = false;
        });
    },
                        // this.$router.push({name: 'instanceDetail', query: {uri: this.uri}})

    async checkUser() {
        this.$parent.$parent.spinner = true
        /* 
        判断是否有传入token
        登录：https://www.cnbksy.com/jdLogin?targetUrl=https://tushu.cnbksy.com?ss
        返回token：https://jdts.library.sh.cn/?ss&token=6fd70427739110ab86b4a2f427423bb2e0c1cc2707665536f676fb4dda7a7ff6af8503d1c564ea39f86392a3848ec58ee7590403f3aee5947c0f9838e5f61396#/
        router(路由配置) 需修改为 mode: 'history' 模式
        通过 this.$route.query.xxx 获取
        */
        if(!sessionStorage.getItem('token')) {
            sessionStorage.setItem('token', this.$route.query.token||'')
        }
        if(sessionStorage.getItem('token')&&!sessionStorage.getItem('orgName')) {
            
            await axios.post(accountAuthtication, {params: {token: sessionStorage.getItem('token')}}).then(response => {
                if (response.data.result==0) {
                    this.$parent.$parent.$refs.header.orgName = response.data.data.username
                    sessionStorage.setItem('orgName', response.data.data.username)
                    this.$router.push({name: 'instanceDetail', query: {uri: this.uri}})
                } else {
                    this.visibleUser = true
                }
            });
        }
        if(sessionStorage.getItem('token')&&sessionStorage.getItem('orgName')) {
            this.$router.push({name: 'instanceDetail', query: {uri: this.uri}})
        }
        this.$parent.$parent.spinner = false
    },

    // 全文浏览埋点
    async buryingPoint() {
        await axios.post(reportPreview, {
            token: sessionStorage.getItem('token'),
            entityId: this.fullTextPath,
            browseSource: "GENERALSEARCH",
            searchActivityId: "",
        }).then(response => {
            if (response.data.status==0) {
                // 成功
            } else {
                // 失败
            }
        });
    },

    login() {
        window.location = 'https://dhapi.library.sh.cn/management/webapi/cenofmagent/token/locpage?systemId=20&durl=https://jdts.library.sh.cn'
    },

    ConfirmError(){
        this.visibleUser = false
    },
    async logout() {
        this.$parent.$parent.spinner = true
        this.visibleLook = false
        sessionStorage.setItem('token', '')
        sessionStorage.setItem('orgName', '')                    
        this.$router.push({name: 'instanceDetail', query: {uri: this.uri}})

        location.reload()
    },

    quit() {
        window.opener = null;
        window.open("about:blank", "_self").close()
    },

    // 跳转至该责任者的详细信息 (人名规范库页面)
    toContributionPerson(uri){
        window.open(uri, '_blank');
    },

    toInstanceSearch(type, value) {
        if(type=='title') {
            this.$router.push({name: 'advanceSearch',
                params: {
                    title: value
                }
            })
        }
        if(type=='publisher') {
            this.$router.push({name: 'advanceSearch',
                params: {
                    publisher: value
                }
            })
        }
        if(type=='publication') {
            this.$router.push({name: 'advanceSearch',
                params: {
                    publication: value
                }
            })
        }
        if(type=='theme') {
            this.$router.push({name: 'advanceSearch',
                params: {
                    theme: value
                }
            })
        }
    },

  },
};
</script>

<style scoped lang="less">
    .cover {
        width: 300px;
        flex: 0 0 auto;
        @media(min-width: 900px){
          width: 400px;
        }
    }
    .info{
        p{
            color: #4c4c4c;
            span{
                color: #666;
            }
        }
    }
    .hand{
        cursor: pointer;
    }
    .ant-btn-primary {
		background-color: #661112;
		border-color: #661112;
	}
</style>
